#import "CommonDetailWebServices.h"
#import "CommonUtil.h"


@implementation CommonDetailWebServices

@synthesize webData;
@synthesize xmlParser;
@synthesize data;
@synthesize dataTable, dataType, element, bookItem;
@synthesize isRowBegin;
@synthesize isValueBegin;
@synthesize owner;

- (void)setDelegate:(NSObject<CommonDetailWebServicesProtocol> *) object {
	owner = object;
}

- (NSDictionary *)getWebServicesData:(NSString *)column page:(NSString *)page {
	[self webServicesRequest:column page:page];
}

- (void)webServicesRequest:(NSString *)column page:(NSString *)page {
	NSString *soapMessage = [NSString stringWithFormat:
                             @"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
                             "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
                             "<soap:Header>\n"
                             "<Authentication>\n"
                             "<username>%@</username>\n"
                             "<password>%@</password>\n"
                             "</Authentication>\n"
                             "</soap:Header>\n"
                             "<soap:Body>\n"
                             "<getBookCn xmlns=\"http://www.oz77.com/\">\n"
                             "<in0></in0>\n"
                             "<in1>%@</in1>\n"
                             "</getBookCn>\n"
                             "</soap:Body>\n"
                             "</soap:Envelope>\n", kWSUsername, kWSPassword, column
                             ];
	//NSLog(soapMessage);
	
	//NSURL *url = [NSURL URLWithString:@"http://192.168.1.101:8080/changjiangpress/services/OzService"];
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@services/OzService", kServerURL]];
	NSMutableURLRequest *connectionRequest = [NSMutableURLRequest requestWithURL:url];
	NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMessage length]];
	
	[connectionRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
	[connectionRequest addValue: [NSString stringWithFormat:@"%@services/OzService/getBookCn", kServerURL] forHTTPHeaderField:@"SOAPAction"];
	[connectionRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
	[connectionRequest setHTTPMethod:@"POST"];
	[connectionRequest setTimeoutInterval:10.0];
	[connectionRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
	[connectionRequest setCachePolicy:NSURLRequestUseProtocolCachePolicy];
	
	/*请求：同步获取数据
	NSData *data = [NSURLConnection sendSynchronousRequest:connectionRequest
										 returningResponse:nil error:nil];
	
	NSString *str = [[NSString alloc]initWithData: data encoding: NSUTF8StringEncoding];
	NSLog(@">>%@", str);
	 */
	
	//请求：异步获取数据
	NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:connectionRequest delegate:self];
	
	//如果连接已经建好，则初始化data
	if( theConnection ) {
		webData = [[NSMutableData data] retain];
	} else {
		NSLog(@"connection is disabled.");
	}
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	[webData setLength: 0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	[webData appendData:data];
}

//如果电脑没有连接网络，则出现此信息（不是网络服务器不通）
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	[connection release];
	[webData release];
	[owner onCommonWebServicesFaild:@"didFailWithError"];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	NSString *theXML = [[NSString alloc] initWithBytes:[webData mutableBytes] 
												length:[webData length] 
											  encoding:NSUTF8StringEncoding];
	//NSLog(@"source DATA:%@", theXML);
	theXML = [theXML stringByReplacingOccurrencesOfString:@"&lt;" withString:@"<"];
	theXML = [theXML stringByReplacingOccurrencesOfString:@"&gt;" withString:@">"];
	theXML = [theXML stringByReplacingOccurrencesOfString:@"&quot;" withString:@"\""];
	
	@try {
		theXML = [CommonUtil getSubstring:theXML prefix:@"<book>" suffix:@"</book>"];
		//NSLog(@"real DATA:%@\n", theXML);
		//如果不是规则化数据，报错
		if( [theXML isEqualToString:@""] ) {
			NSLog(@"数据格式不错");
			[owner onCommonDetailWebServicesFaild:@"dataFormatError"];
			return;	
		}
	}
	@catch (NSException *e) {
		NSLog(@"NSException");
		[owner onCommonDetailWebServicesFaild:@"NSException"];
		return;
	}
	//NSLog(@"real DATA:%@", theXML);
	webData = nil;
	webData = [[NSMutableData alloc] init];
	[webData appendData:[theXML dataUsingEncoding:NSUTF8StringEncoding]];
	
	if( xmlParser ) {
		[xmlParser release];
	}
	
	dataTable = [[NSMutableArray alloc] init];
	dataType = 0;
	itemValueTmp = [[NSString alloc] init];
	element = [[NSMutableArray alloc] init];
	bookItem = [[BookItem alloc] init];
	
	xmlParser = [[NSXMLParser alloc] initWithData: webData];
	[xmlParser setDelegate: self];
	[xmlParser setShouldResolveExternalEntities: YES];
	[xmlParser parse];
	
	[connection release];
	[webData release];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName 
  namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *)qName 
	attributes: (NSDictionary *)attributeDict {
	
	/*
     <book><id>1323470943086</id><code>com.cjcb.books.simpleworld</code><name>平凡的世界</name><engname></engname><icon>1323470943086_1.png</icon><iconsmall>1323470943086_1.png</iconsmall><shot></shot><phone>1323470943086_3.zip</phone><phonetype>txt</phonetype><pad>1323470943086_4.zip</pad><padtype>pdf</padtype><series></series><price>0</price><price2></price2><priceprint></priceprint><language></language><author>路遥</author><translator></translator><press></press><presstime></presstime><issn></issn><pages>0</pages><words></words><score>0</score><category>1003</category><hot>1</hot><star>5</star><download>0</download><favorite>0</favorite><editorinfo><![CDATA[]]></editorinfo><contentinfo><![CDATA[]]></contentinfo><authorinfo><![CDATA[]]></authorinfo><catalog><![CDATA[]]></catalog><freecontent><![CDATA[]]></freecontent><approvaltime></approvaltime></book>
     */
	
    //选定列
    if([[elementName uppercaseString] isEqualToString:@"ID"] ||
       [[elementName uppercaseString] isEqualToString:@"ENGNAME"] ||
       [[elementName uppercaseString] isEqualToString:@"ICON"]||
       [[elementName uppercaseString] isEqualToString:@"SHOT"]||
       [[elementName uppercaseString] isEqualToString:@"SERIES"]||
       
       [[elementName uppercaseString] isEqualToString:@"PRICEPRINT"]||
       [[elementName uppercaseString] isEqualToString:@"LANGUAGE"]||
       [[elementName uppercaseString] isEqualToString:@"ISSN"]||
       [[elementName uppercaseString] isEqualToString:@"PAGES"]||
       [[elementName uppercaseString] isEqualToString:@"WORDS"]||
       
       [[elementName uppercaseString] isEqualToString:@"SCORE"]||       
       [[elementName uppercaseString] isEqualToString:@"EDITORINFO"]||
       [[elementName uppercaseString] isEqualToString:@"CONTENTINFO"]||
       [[elementName uppercaseString] isEqualToString:@"AUTHORINFO"]||
       [[elementName uppercaseString] isEqualToString:@"CATALOG"]||
       
       [[elementName uppercaseString] isEqualToString:@"FREECONTENT"]||
       [[elementName uppercaseString] isEqualToString:@"PRESS"]||
       [[elementName uppercaseString] isEqualToString:@"PRESSTIME"]
       ) {
        isValueBegin = YES;
    }
} 

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { 
	if(isValueBegin) {
		itemValueTmp = [itemValueTmp stringByAppendingString:string];
	}
} 

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName 
  namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { 
	if ([[elementName uppercaseString] isEqualToString:@"ID"]) {
		bookItem.bookId = itemValueTmp; isValueBegin = NO; itemValueTmp = @"";
	}else if ([[elementName uppercaseString] isEqualToString:@"ENGNAME"]) {
		bookItem.bookEnglishName = itemValueTmp;isValueBegin = NO; itemValueTmp = @"";
	}else if ([[elementName uppercaseString] isEqualToString:@"ICON"]) {
		bookItem.bookIcon = itemValueTmp;isValueBegin = NO; itemValueTmp = @"";
	}else if ([[elementName uppercaseString] isEqualToString:@"SHOT"]) {
		bookItem.bookShot = itemValueTmp;isValueBegin = NO; itemValueTmp = @"";
	}else if ([[elementName uppercaseString] isEqualToString:@"SERIES"]) {
		bookItem.bookSeries = itemValueTmp;isValueBegin = NO; itemValueTmp = @"";
	}else if ([[elementName uppercaseString] isEqualToString:@"PRICEPRINT"]) {
		bookItem.bookPricePrint = itemValueTmp;isValueBegin = NO; itemValueTmp = @"";
	}else if ([[elementName uppercaseString] isEqualToString:@"LANGUAGE"]) {
		bookItem.bookLanguage = itemValueTmp;isValueBegin = NO; itemValueTmp = @"";
	}else if ([[elementName uppercaseString] isEqualToString:@"ISSN"]) {
		bookItem.bookIssn = itemValueTmp;isValueBegin = NO; itemValueTmp = @"";
	}else if ([[elementName uppercaseString] isEqualToString:@"PAGES"]) {
		bookItem.bookPages = itemValueTmp;isValueBegin = NO; itemValueTmp = @"";
	}else if ([[elementName uppercaseString] isEqualToString:@"WORDS"]) {
		bookItem.bookWords = itemValueTmp;isValueBegin = NO; itemValueTmp = @"";
	}else if ([[elementName uppercaseString] isEqualToString:@"SCORE"]) {
		bookItem.bookScore = itemValueTmp;isValueBegin = NO; itemValueTmp = @"";
	}else if ([[elementName uppercaseString] isEqualToString:@"EDITORINFO"]) {
		bookItem.bookEditorInfo = itemValueTmp;isValueBegin = NO; itemValueTmp = @"";
	}else if ([[elementName uppercaseString] isEqualToString:@"CONTENTINFO"]) {
		bookItem.bookContentInfo = itemValueTmp;isValueBegin = NO; itemValueTmp = @"";
	}else if ([[elementName uppercaseString] isEqualToString:@"AUTHORINFO"]) {
		bookItem.bookAuthorInfo = itemValueTmp;isValueBegin = NO; itemValueTmp = @"";
	}else if ([[elementName uppercaseString] isEqualToString:@"CATALOG"]) {
		bookItem.bookCatalog = itemValueTmp;isValueBegin = NO; itemValueTmp = @"";
	}else if ([[elementName uppercaseString] isEqualToString:@"FREECONTENT"]) {
		bookItem.bookFreeContent= itemValueTmp;isValueBegin = NO; itemValueTmp = @"";
	}else if ([[elementName uppercaseString] isEqualToString:@"PRESS"]) {
		bookItem.bookPress = itemValueTmp;isValueBegin = NO; itemValueTmp = @"";
	}else if ([[elementName uppercaseString] isEqualToString:@"PRESSTIME"]) {
		bookItem.bookPressTime = itemValueTmp;isValueBegin = NO; itemValueTmp = @"";
	}else if([[elementName uppercaseString] isEqualToString:@"BOOK"]) {
        [dataTable addObject:bookItem];
		data = [[NSDictionary alloc] initWithObjectsAndKeys:
				[[NSArray alloc] initWithArray:dataTable], @"dataTable",
				nil];
		
		[dataTable release];
		[itemValueTmp release];
		
		[owner onCommonDetailWebServicesOver:data];
		
		[data release];
	}
} 

- (void)parserDidStartDocument:(NSXMLParser *)parser { 
	//NSLog(@"start parse document"); 
} 

- (void)parserDidEndDocument:(NSXMLParser *)parser { 
	//NSLog(@"end parse document"); 
}

@end
